package com.fuful.servlet;

import com.fuful.domain.Product;
import com.fuful.service.ProductService;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PageProductAction extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /**
         * 1.获得请求参数（可无）
         * 2.调用业务逻辑
         * 3.获得结果
         * 4.根据结果判断是否需要共享数据（request/session/application）[类比保存一天、一个月、一年]
         * 5。转发或重定向
         */
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");// 注意设置为UTF-8，否则中文乱码

            Gson gson = new Gson();
            ProductService ps = new ProductService();
            List<Product> listAll =  ps.findByAll();

            int pages = 0;  //判断总页数
            if(listAll.size()%5!=0)
            {
                pages = (listAll.size()/5+1);
            }
            else
            {
                pages = (listAll.size()/5);
            }
            String curPage = request.getParameter("cPage");
            List<Product> list =  null;
            if(Integer.parseInt(curPage) <= pages)
                list = ps.findByPage(Integer.parseInt(curPage));
            else{
                System.out.println("已经没有数据了！");
            }
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("list", list);//list中放返回的数据
            map.put("pages", pages);//pages为总页数

            String info = gson.toJson(map);
            response.getWriter().print(info);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}